package com.mgq.netty.bytebuff;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;


/**
 * @author MaGuangQi
 * @description 传统阻塞模式实例
 * 传统单线程阻塞模式,一次只能处理一个连接,当有多个连接时,无法处理
 *
 * @date 2021-12-02 15:07
 **/
@Slf4j
public class BlockMode {
    public static void main(String[] args) throws IOException {
        //1.ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(16);
        //2.创建一个ServerSocketChannel
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8000));
        List<SocketChannel> channels = new ArrayList<>();
        while (true) {
            //获取连接
            log.debug("connecting......");
            SocketChannel socketChannel = ssc.accept();//阻塞
            log.debug("connected......{}",socketChannel);
            channels.add(socketChannel);
            for (SocketChannel channel : channels) {
                log.debug("before read.......{}",channel);
                channel.read(byteBuffer); //阻塞
                //切换为读模式
                byteBuffer.flip();
                ByteBufferUtil.debugRead(byteBuffer);
                //切换为写模式
                byteBuffer.clear();
                log.debug("after read.......{}",channel);
            }
        }
    }
}
